package com.es.demo.config;

import com.es.demo.constant.Constant;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author shengtao
 * @Description:
 * @date 2018/10/31 19:29
 */
@Configuration
public class ElasticConfig {

    Logger log = LoggerFactory.getLogger(ElasticConfig.class);

    @Bean
    TransportClient transportClient() throws UnknownHostException {
        //创建客户端
        Settings esSettings = Settings.builder()
                .put("cluster.name", "my-application")
//                .put("client.transport.sniff",false)
                .build();
        TransportClient client = new PreBuiltTransportClient(esSettings);

        try {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Constant.ES_HOST), Constant.ES_PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
//        client.close();
        return client;
    }

}
